#include "Renderer_PCH.h"
#include "FramebufferRequest.h"

/*--------------------------------------------------------------------------*/

FramebufferRequest::FramebufferRequest(const std::string& name, const std::string& attachments) :
	m_name(name)
{
	bool readingType = true;
	std::string type;
	std::string texture;

	for (uint i = 0; i < attachments.size(); ++i)
	{
		if (attachments[i] == ' ')
		{
			if (type != "")
			{
				m_attachments[type] = texture;
			}
			
			type = "";
			texture = "";
			readingType = true;
			continue;
		}
		else if (attachments[i] == ':')
		{
			readingType = false;
			continue;
		}

		if (readingType)
		{
			type += attachments[i];
		}
		else
		{
			texture += attachments[i];
		}
	}

	if (type != "")
	{
		m_attachments[type] = texture;
	}

	m_framebuffer = g_Renderer->GetRendererStorageMgr()->CreateFramebuffer(m_name);
	__Check(m_framebuffer);
}

/*--------------------------------------------------------------------------*/

FramebufferRequest::~FramebufferRequest()
{

}

/*--------------------------------------------------------------------------*/

void* FramebufferRequest::DoRequest()
{
	__Check(m_framebuffer);

	glGenFramebuffers(1, &m_framebuffer->m_handle);
	glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer->m_handle);

	RTexture* firstTexture = NULL;
	std::string ds_name = m_attachments["ds"];

	if (ds_name != "")
	{
		RTexture* ds = g_Renderer->GetRendererStorageMgr()->GetTexture(ds_name);
		__Check(ds);

		m_framebuffer->m_depthstencil = ds;
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, ds->GetHandle(), 0);

		firstTexture = ds;
	}

	for (uint i = 0; i < RFRAMEBUFFER_MAX_COLORS; ++i)
	{
		std::string name = "color" + std::to_string(i);
		std::string col_name = m_attachments[name];

		if (col_name != "")
		{
			RTexture* color = g_Renderer->GetRendererStorageMgr()->GetTexture(col_name);
			__Check(color);

			m_framebuffer->m_color[i] = color;
			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, color->GetHandle(), 0);

			if (firstTexture != NULL)
			{
				__Check(firstTexture->GetHeight() == color->GetHeight());
				__Check(firstTexture->GetWidth() == color->GetWidth());
			}
			else
			{
				firstTexture = color;
			}
		}
	}

	__Check(firstTexture);
	m_framebuffer->m_width = firstTexture->GetWidth();
	m_framebuffer->m_heigth = firstTexture->GetHeight();

	GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	__Check(status == GL_FRAMEBUFFER_COMPLETE);
	
	glBindFramebuffer(GL_FRAMEBUFFER, 0);

	__Info("[RENDERER] Framebuffer %s created as %d", m_name.c_str(), m_framebuffer->m_handle);
	return m_framebuffer;
}

/*--------------------------------------------------------------------------*/
